package com.ifonly.ext.freemarker.directive;

import com.ifonly.ext.freemarker.utils.DirectiveUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import java.io.IOException;
import java.util.Map;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-16 15:43
 * @since JDK 1.6
 */
public class OverrideDirective implements TemplateDirectiveModel {

    public final static String DIRECTIVE_NAME = "override";

    @Override
    public void execute(Environment env,
                        Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body) throws TemplateException, IOException {
        String name = DirectiveUtils.getRequiredParam(params, "name");
        String overrideVariableName = DirectiveUtils.getOverrideVariableName(name);

        TemplateDirectiveBodyOverrideWrapper override = DirectiveUtils.getOverrideBody(env, name);
        TemplateDirectiveBodyOverrideWrapper current = new TemplateDirectiveBodyOverrideWrapper(body,env);
        if(override == null) {
            env.setVariable(overrideVariableName, current);
        }else {
            DirectiveUtils.setTopBodyForParentBody(env, current, override);
        }
    }


}
